package dyyx.util;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

public class WebAction {

	public static final String DATA = "data";
	public static final String ERROR = "error";
	
	
	public static void runSql(HttpServletRequest request, Map<String, Object> context) throws Exception{
		if (request == null || context == null) {
			return;
		}
		try{
		    runSql_(request,context) ;
		}catch(Throwable e){
			context.put(ERROR, e);
		}
	}


	private static void runSql_(HttpServletRequest request, Map<String, Object> context) throws Exception{
		if (request == null || context == null) {
			return;
		}
		
		int maxRows = WebUtil.getInt(request, "maxRows");
		
		if(maxRows<=0 || maxRows >1000){
			maxRows = 100;
		}
		context.put("maxRows", maxRows);

		
		String optype = WebUtil.getString(request, "optype");

		String checkResult = checkOptype(optype);
		if (checkResult != null) {
			context.put(ERROR, checkResult);
			return;
		}

		String sql = WebUtil.getString(request, "sql");

		if (StringUtils.isBlank(sql)) {
			context.put(ERROR, "sql_blank");
			return;
		}

		context.put("optype", optype);

		List<String> params = WebUtil.getList(request, "params");
		Object[] paramsArray = null;
		if (params != null && params.size() > 0) {
			paramsArray = params.toArray();
		}

		if ("update".equals(optype)) {		
			int result = JdbcUtil.executeUpdate(sql, paramsArray);		
			context.put(DATA, result);
			return;
		}

		if ("query".equals(optype)) {			
			List<Map<String,String>> result = JdbcUtil.queryAsMap(sql, paramsArray, maxRows);
			context.put(DATA, result);
			return;
		}

	}

	public static String checkOptype(String optype) {
		if (StringUtils.isBlank(optype)) {
			return "optype_blank";
		}

		if ("update".equals(optype)) {
			return null;
		}

		if ("query".equals(optype)) {
			return null;
		}

		return "optype_error";
	}

}
